const express = require('express')
const router = express.Router()
const joi = require('joi')
const Response = require('../utils/Response.js')

const pool = require('../utils/db.js')

// 注册
router.post('/user_info/add',(req,resp)=>{
  let {
    user_phone,
    user_password,
  } = req.body;

  let schema = joi.object({
    user_phone:joi.number().required(),
    user_password:joi.string().required()
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  let sql = "insert into user (user_phone, user_password) values (?,?)";
  pool.query(sql, [user_phone,  user_password], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
})


// ==>查询 
router.get("/user_info/query", (req, resp) => {
  let { id } = req.query;
  // 表单验证
  let schema = joi.object({
    id: joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }

  // 执行查询业务
  let sql = "select * from user where id=?";
  pool.query(sql, [id], (error, result) => {
    if (error && result.data) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result && result.length == 0) {
      // 没查到
      resp.send(Response.ok(null));
    } else {
      resp.send(Response.ok(result[0]));
    }
  });
});



// ==>修改
router.post("/user_info/update", (req, resp) => {
  let {
    user_phone,
    user_name,
    user_email,
    user_password,
    user_age,
    user_sex,
    user_describe,
    user_src,
    id,
  } = req.body; // post请求参数在req.body中

  // 表单验证
  // let schema = joi.object({
  //   id: joi.string().required(),
  //   user_phone: joi.number().required(),
  //   user_password: joi.required(),
  // });
  // let { error, value } = schema.validate(req.body);
  // if (error) {
  //   resp.send(Response.error(400, error));
  //   return; // 结束
  // }

  // 表单验证通过，执行更新电影信息操作
  let sql = `update user set user_phone=?, user_name=?, user_email=?, user_password=?, user_age=?, user_sex=?, user_describe=?, user_src=? where id=?`;
  pool.query(
    sql,
    [
      user_phone,
      user_name,
      user_email,
      user_password,
      user_age,
      user_sex,
      user_describe,
      user_src,
      id,
    ],
    (error, result) => {
      if (error) {
        resp.send(Response.error(500, error));
        throw error;
      }
      resp.send(Response.ok());
    }
  );
});

// 将router对象导出
module.exports = router;
